<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/operationsummary/Operations' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>药品信息维护</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="药品类型：">
        <!-- 可清空下拉框 -->
        <el-select
          size="small"
          clearable
          v-model="searchForm.drugClassId"
          placeholder=""
        >
          <!--根据字典表生成下拉选项-->
          <el-option
            v-for="(label, value) in drugDict.class"
            :key="value"
            :label="label"
            :value="Number(value)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期：">
        <DateTimeRange @callFather="handleDateTimeRange"></DateTimeRange>
      </el-form-item>
      <el-form-item label="关键字：">
        <el-input
          size="small"
          v-model="searchForm.keyword"
          placeholder="输入药品名称/药品编码/拼音"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column sortable prop="id" label="序号" width="100">
      </el-table-column>
      <el-table-column sortable prop="code" label="编码" width="100">
      </el-table-column>
      <el-table-column sortable prop="commonName" label="药品名称" width="200">
      </el-table-column>
      <el-table-column sortable prop="classId" label="类型" width="100">
        <template slot-scope="scope">
          <!--将classID转换为字典中的字符串显示（模型中的数据不会改变）-->
          <div>{{ drugDict.class[scope.row.classId] }}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="norm" label="规格" width="100">
        <template slot-scope="scope">
          <div>
            {{ scope.row.doseFactor }}{{ drugDict.unit[scope.row.doseUnit] }}*{{
              scope.row.basicFactor
            }}{{ drugDict.unit[scope.row.basicUnit] }}/{{
              drugDict.unit[scope.row.unitId]
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="cost" label="采购单价" width="100">
        <template slot-scope="scope">
          <!--将查到的价格(单位:分)转换单位(元)进行显示-->
          <div>{{ scope.row.cost / 100 }}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="price" label="售药单价" width="100">
        <template slot-scope="scope">
          <div>{{ scope.row.price / 100 }}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="factoryId" label="生产厂家" width="200">
        <template slot-scope="scope">
          <div>{{ drugDict.factory[scope.row.factoryId] }}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="isEnable" label="状态" width="100">
        <template slot-scope="scope">
          <div>{{ drugDict.enable[scope.row.isEnable] }}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="createDate" label="创建时间" width="200">
        <template slot-scope="scope">
          <div>{{ scope.row.createDate | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="deleteMedicine(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="handlePageEvent"
    ></Pagination>

    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="400px"
      @click="closeDialog"
    >
      <el-form
        label-width="35%"
        :model="editMedicine"
        :rules="rules"
        ref="editMedicine"
      >
        <el-form-item label="药品编码" prop="code">
          <el-input
            size="small"
            class="edit-input"
            v-model="editMedicine.code"
            disabled
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="药品条形码" prop="barCode">
          <el-input
            size="small"
            class="edit-input"
            v-model="editMedicine.barCode"
            auto-complete="off"
            placeholder="药品条形码"
          ></el-input>
        </el-form-item>
        <el-form-item label="药品通用名" prop="commonName">
          <el-input
            size="small"
            class="edit-input"
            v-model="editMedicine.commonName"
            auto-complete="off"
            placeholder="请输入药品通用名"
          ></el-input>
        </el-form-item>
        <el-form-item label="拼音码" prop="pinyinCode">
          <el-input
            size="small"
            class="edit-input"
            v-model="editMedicine.pinyinCode"
            auto-complete="off"
            placeholder="请输入拼音码"
          ></el-input>
        </el-form-item>
        <el-form-item label="药品分类" prop="classId">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.classId"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.class"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品剂型" prop="formId">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.formId"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.form"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="OTC药品" prop="otc">
          <el-radio-group v-model="editMedicine.otc">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发票项目" prop="invoiceId">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.invoiceId"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.invoice"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="批准文号" prop="approvalNo">
          <el-input
            size="small"
            class="edit-input"
            v-model="editMedicine.approvalNo"
            placeholder="请输入批准文号"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="生产厂家" prop="factoryId">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.factoryId"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.factory"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药品状态" prop="isEnable">
          <el-radio-group v-model="editMedicine.isEnable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <hr />
        <el-form-item label="包装单位" prop="unitId">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.unitId"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.unit"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本系数" prop="basicFactor">
          <el-input-number
            size="small"
            v-model="editMedicine.basicFactor"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="基本单位" prop="basicUnit">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.basicUnit"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.unit"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="剂量系数" prop="doseFactor">
          <el-input-number
            size="small"
            v-model="editMedicine.doseFactor"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="剂量单位" prop="doseUnit">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.doseUnit"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.unit"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购单价(元)" prop="cost">
          <el-input-number
            size="small"
            :precision="2"
            :step="0.1"
            :min="0"
            v-model="editMedicine.cost"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="零售单价(元)" prop="price">
          <el-input-number
            size="small"
            :precision="2"
            :step="0.1"
            :min="0"
            v-model="editMedicine.price"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="允许拆零" prop="allowSplit">
          <el-radio-group v-model="editMedicine.allowSplit">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="允许会员折扣" prop="allowDiscount">
          <el-radio-group v-model="editMedicine.allowDiscount">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <hr />
        <el-form-item label="用法" prop="usageId">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.usageId"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.usage"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="'单次用量(' + drugDict.unit[editMedicine.doseUnit] + ')'"
          prop="price"
        >
          <el-input-number
            size="small"
            :min="1"
            v-model="editMedicine.dosePerTime"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="频度" prop="frequency">
          <el-select
            size="small"
            class="edit-input"
            v-model="editMedicine.frequency"
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option
              v-for="(label, value) in drugDict.frequency"
              :key="value"
              :label="label"
              :value="Number(value)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <hr />
        <el-form-item label="库存下限" prop="waterMarkLow">
          <el-input-number
            size="small"
            v-model="editMedicine.waterMarkLow"
            :min="10"
            :max="30"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="库存上限" prop="waterMarkHeigh">
          <el-input-number
            size="small"
            v-model="editMedicine.waterMarkHeigh"
            :min="100"
            :max="200"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="waterMark">
          <el-input-number
            size="small"
            :min="0"
            v-model="editMedicine.waterMark"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="有效期至" prop="validPeriod">
          <el-date-picker
            size="small"
            v-model="editMedicine.validPeriod"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="药品说明" prop="description">
          <el-input
            type="textarea"
            size="small"
            class="edit-input"
            v-model="editMedicine.description"
            auto-complete="off"
            placeholder="请输入药品说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            size="small"
            class="edit-input"
            v-model="editMedicine.remark"
            auto-complete="off"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm(editMedicine)"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入药品类型字典
import { drugDict } from "../../dict/drugDict";
import Pagination from "../../components/Pagination";
// 引入时间段选择组件
import DateTimeRange from "../../components/DateTimeRange";
// 引入 Axios
import axios from "axios";

export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: "添加",
      editMedicine: {},
      // rules表单验证
      rules: {
        commonName: [
          { required: true, message: "请输入药品通用名", trigger: "blur" },
        ],
        classId: [
          { required: true, message: "请选择药品分类", trigger: "blur" },
        ],
        form: [{ required: true, message: "请选择药品剂型", trigger: "blur" }],
        factoryId: [
          { required: true, message: "请选择生产厂家", trigger: "blur" },
        ],
        validPeriod: [
          { required: true, message: "请选择有效期限", trigger: "blur" },
        ],
      },
      // 搜索框数据
      searchForm: {
        keyword: "",
        drugClassId: null,
        dateTimeRange: null,
      },
      // 删除部门
      seletedata: {
        ids: "",
        token: localStorage.getItem("logintoken"),
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      drugDict: drugDict, // 药品相关字典
    };
  },
  // 注册组件
  components: {
    Pagination,
    DateTimeRange,
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline);
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取数据
    getdata() {
      this.loading = true;
      // 待提交的数据
      let dto = {
        pageNum: this.pageparm.pageNum,
        pageSize: this.pageparm.pageSize,
      };
      // 根据 this.searchForm 进行构建 dto
      if (this.searchForm.keyword !== "")
        dto.keywords = this.searchForm.keyword;
      if (this.searchForm.drugClassId !== null) {
        if (dto.medicine === undefined) dto.medicine = {};
        dto.medicine.classId = this.searchForm.drugClassId;
      }
      if (this.searchForm.dateTimeRange !== null) {
        dto.startDate = this.searchForm.dateTimeRange[0];
        dto.endDate = this.searchForm.dateTimeRange[1];
      }
      // 发送请求
      axios
        .post("/api/medicine/select", dto)
        .then((res) => {
          if (res.data.data == null) {
            throw "error";
          }
          return res.data.data;
        })
        .then((data) => {
          this.listData = data.list;
          this.pageparm.pageNum = data.pageNum;
          this.pageparm.pageSize = data.pageSize;
          this.pageparm.total = data.total;
        })
        .catch((err) => {
          this.editFormVisible = false;
          this.loading = false;
          this.$message.error("获取数据失败，请稍后再试！");
        });

      this.loading = false;
    },
    // 分页插件事件
    handlePageEvent(parm) {
      this.pageparm.pageNum = parm.currentPage;
      this.pageparm.pageSize = parm.pageSize;
      this.getdata();
    },
    // 时间段选择事件
    handleDateTimeRange(param) {
      this.searchForm.dateTimeRange = param;
    },
    // 搜索事件
    search() {
      this.pageparm.pageNum = 1;
      this.getdata();
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      if (row != undefined && row != "undefined") {
        // 浅克隆
        this.editMedicine = Object.assign({}, row);
        // 显示价格单位换算
        this.editMedicine.cost = this.editMedicine.cost / 100;
        this.editMedicine.price = this.editMedicine.price / 100;
        this.editFormVisible = true;
        this.title = "修改";
      } else {
        this.title = "添加";
        // 模型默认值
        let dateTime = new Date();
        dateTime.setFullYear(new Date().getFullYear() + 2);
        this.editMedicine = {
          otc: 0,
          doseUnit: 5,
          basicFactor: 1,
          isEnable: 1,
          doseFactor: 1,
          invoiceId: 4,
          waterMarkLow: 30,
          waterMark: 0,
          waterMarkHeigh: 200,
          allowDiscount: 0,
          allowSplit: 0,
          cost: 1.0,
          price: 1.2,
          validPeriod: dateTime,
        };
        axios
          .get("/api/medicine/generateCode")
          .then((res) => {
            if (res.data.data == null) {
              throw "error";
            }
            return res.data.data;
          })
          .then((data) => {
            this.editMedicine.code = data;
            this.editFormVisible = true;
          })
          .catch((err) => {
            this.editFormVisible = false;
            this.loading = false;
            this.$message.error("生成药品编码失败，新增功能暂时不可用！");
          });
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      editData.cost = editData.cost * 100;
      editData.price = editData.price * 100;
      axios
        .post("/api/medicine/update", editData)
        .then((res) => {
          this.editFormVisible = false;
          this.loading = false;
          if (res.data !== undefined && res.data.code === 200) {
            this.currentPage = 1;
            this.getdata();
            this.$message({
              type: "success",
              message: "保存成功！",
            });
          } else {
            this.$message({
              type: "info",
              message: "保存失败！",
            });
          }
        })
        .catch((err) => {
          this.editFormVisible = false;
          this.loading = false;
          this.$message({
            type: "error",
            message: "保存失败，请稍后再试！",
          });
        });
    },
    // 删除药品
    deleteMedicine(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .get("/api/medicine/delete/" + row.id)
            .then((res) => {
              if (res.data !== undefined && res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "药品已删除!",
                });
                this.getdata();
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
    },
  },
};
</script>

<style scoped>
hr {
  border-style: dashed;
  color: gainsboro;
}
.edit-input {
  width: 75%;
}

.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 
 